#include<iostream>
#include<cstdlib>
#include<unistd.h>
using namespace std;

bool GetQueryString(std::string &query_string)
{
    bool result =false;
    //用cerr打印是因为0和1文件描述符被重定向到管道了
    std::string method = getenv("METHOD");
    cerr << "Debug test: " << getenv("METHOD") << endl;
    if("GET" == method) 
    {
        query_string = getenv("QUERY_STRING");  
        cerr << "Get Debug QUERY_STRING: " << query_string <<endl;
        result = true;
    }
    else if("POST" == method)
    {
        //从环境变量中知道要在重定向后标准输入中读取父进程给他发来的数据的多少字节
        cerr << "Content-Length: " <<getenv("CONTENT_LENGTH") <<endl;
        int content_length = atoi(getenv("CONTENT_LENGTH"));
        char c = 0;
        while(content_length)
        {
            read(0,&c,1);//从0文件描述符读，每次读一个字节
            query_string.push_back(c);//把读到的内容push进字符串
            content_length--;
        }
        cerr << "Post Debug QUERY_STRING: " << query_string <<endl;
        result = true;
    }
    else
    {
        result = false;
    }
    return result;
}

//一个字符串分割为两个子串
void CutString(std::string &in,const std::string &sep,
    std::string &out1,std::string &out2)
{
    auto pos = in.find(sep);
    if(std::string::npos != pos)
    {
        out1 = in.substr(0,pos);
        out2 = in.substr(pos+sep.size());//第二个字串截取就从pos+分隔符数量的位置开始截取
    }
}

int main()
{   
    std::string query_string;
    GetQueryString(query_string);
    //a=100&b=200

    std::string str1;
    std::string str2;
    CutString(query_string, "&", str1, str2);

    std::string name1;
    std::string value1;
    CutString(str1, "=", name1, value1);

    std::string name2;
    std::string value2;
    CutString(str2, "=", name2, value2);

    //写入1里文件描述符里（其实就是写入管道里）
    std::cout << name1 << " : " << value1 << std::endl;
    std::cout << name2 << " : " << value2 << std::endl;

    //2
    std::cerr << name1 << " : " << value1 << std::endl;
    std::cerr << name2 << " : " << value2 << std::endl;

    return 0;
}